package in.wenwen.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import in.wenwen.dto.ArticleDto;
import in.wenwen.dto.QueryDto;
import in.wenwen.entity.User;
import in.wenwen.handler.IndexHandler;
import in.wenwen.service.IArticleService;
import in.wenwen.service.IUserService;
import in.wenwen.util.ConstUtil;
import in.wenwen.util.Page;
import in.wenwen.util.UserManage;

import org.jiucheng.ioc.annotation.Inject;
import org.jiucheng.util.StringUtil;
import org.jiucheng.web.annotation.Controller;
import org.jiucheng.web.annotation.Controller.GET;

@Controller(IndexHandler.class)
public class UController {
    
    @Inject
    private IArticleService articleService;
    @Inject
    private IUserService userService;
    
    @GET("/u/([0-9a-zA-Z]+)")
    public String u(String[] args, HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = userService.findUserByUid(UserManage.getWebappId(), args[1]);
        if(null == user) {
            response.sendError(404);
            return null;
        }
        String pStr = request.getParameter("p");//当前页
        int p = 1;
        if(StringUtil.isNotBlank(pStr) && pStr.matches("[0-9]+")) {
            p = Integer.parseInt(pStr);
        }
        QueryDto queryDto = new QueryDto();
        queryDto.setUserId(user.getId());
        queryDto.setWebappId(UserManage.getWebappId());
        queryDto.setPageIndex(p);
        Page<ArticleDto> page = articleService.pageS(queryDto);
        page.setUrl("u/" + args[1] + "?p={0}");
        request.setAttribute("page", page);
        return ConstUtil.getUri("index");
    }
}
